﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using road2.Model;

namespace road2.code
{
    public static class CarCollectionExtensions
    {
        public static IEnumerable<CarClass> CarsOnRoad(this IEnumerable<CarClass> cars, RoadClass road)
        {
            return cars.Where(car => car.Road == road);
        }

        public static IEnumerable<CarClass> CarsInLine(this IEnumerable<CarClass> cars, int line)
        {
            return cars.Where(car => car.Line == line);
        }

        public static IEnumerable<CarClass> CarsInFront(this IEnumerable<CarClass> cars, int distance)
        {
            return cars.Where(car => car.Distance >= distance);
        }

        public static IEnumerable<CarClass> CarsBehind(this IEnumerable<CarClass> cars, int distance)
        {
            return cars.Where(car => car.Distance < distance);
        }

        public static CarClass NearestCarInFront(this IEnumerable<CarClass> cars, int distance, int line)
        {
            var tmpCars = cars.CarsInLine(line).CarsInFront(distance).OrderBy(car => car.Distance);

            if (tmpCars.Count() != 0)
            {
                return tmpCars.First();
            }

            return null;
        }

        public static CarClass NearestCarBehind(this IEnumerable<CarClass> cars, int distance, int line)
        {
            var tmpCars = cars.CarsInLine(line).CarsBehind(distance).OrderByDescending(car => car.Distance);

            if (tmpCars.Count() != 0)
            {
                return tmpCars.First();
            }

            return null;
        }

        public static IEnumerable<CarClass> NearestCars(this IEnumerable<CarClass> cars, CarClass car)
        {
            var tmpCars = cars.CarsOnRoad(car.Road);
            List<CarClass> tmpNCars = new List<CarClass>();

            for (int i = car.Line - 1; i <= car.Line + 1; i++)
            {
                CarClass NC = tmpCars.NearestCarInFront(car.Distance, i);
                if (NC != null)
                {
                    tmpNCars.Add(NC);
                }
                NC = tmpCars.NearestCarBehind(car.Distance, i);
                if (NC != null)
                {
                    tmpNCars.Add(NC);
                }
            }

            return tmpNCars;
        }
    }
}
